package service;
import dao.BookMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pojo.Books;
import pojo.PageBean;
import java.util.List;
@Service
public class BookServiceImpl implements  BookService{
    private BookMapper bookMapper;
    @Autowired
    public void setBookMapper (BookMapper bookMapper){
        this.bookMapper=bookMapper;
    }
    @Override
    public int addBook(Books books) {
        return bookMapper.addBook(books);
    }
    @Override
    public int delete(int id) {
        return bookMapper.delete(id);
    }
    @Override
    public int updateBook(Books books) {
        return bookMapper.updateBook(books);
    }
    @Override
    public Books queryBookByID(int id) {
      return   bookMapper.queryBookByID(id);
    }

    @Override
    public List<Books> queryAllBook() {
        return bookMapper.queryAllBook();
    }

    @Override
    public PageBean<Books> queryBookByKeyword(int currentPage, int rows, String keyword, String keyword2) {
        //防止错误操作
        if (currentPage<=0){
            currentPage=1;
        }
        //首次登陆设置起始页为1
        //在这里就先预处理防止当前页码数超过总页码数
        PageBean<Books> pageBean=new PageBean<Books>();
        pageBean.setStartPage(1);//定死我就不信信息还能这么少
        pageBean.setEndPage(3);//结束页为三
        //设置总记录数
        int totalCount = bookMapper.findTotalCount(keyword, keyword2);
        pageBean.setTotalCount(totalCount);
        //设置页码三目运算
        int totalPage=(pageBean.getTotalCount() % rows)==0 ?pageBean.getTotalCount()/rows : (pageBean.getTotalCount()/rows)+1;
        pageBean.setTotalPage(totalPage);
        if (currentPage>totalPage){
            currentPage=totalPage;
            if (currentPage<=0){
                currentPage=1;
            }
        }
        //根据条件查询到的list集合
        pageBean.setList(bookMapper.queryBookByKeyword((currentPage-1)*rows,rows,keyword,keyword2));
        //设置当前页
        pageBean.setCurrentPage(currentPage);
        //设置每一页显示的记录数
        //如果当前页大于结束页
        if (currentPage>pageBean.getEndPage()){
            //令当前页为结束页+1
            pageBean.setStartPage(pageBean.getEndPage()+1);
            //并将结束页加2
            pageBean.setEndPage(pageBean.getStartPage()+2);
        }
        if (pageBean.getEndPage()>totalPage){
            pageBean.setEndPage(totalPage);
        }
        pageBean.setRows(rows);
        return pageBean;
    }
    @Override
    public Books queryBookByBookName(String bookName) {
        return bookMapper.queryBookByBookName(bookName);
    }

    @Override
    public int findTotalCount(String string_01, String string_02) {
        return bookMapper.findTotalCount(string_01,string_02);
    }
}
